﻿using System;
using System.Collections.Generic;
using System.Linq;
using Cirrious.MvvmCross.Plugins.Sqlite;

namespace Bulb.Core.Services.DataStore
{
    public class Repository<T> : IRepository<T> where T : class, new()
    {
        private readonly ISQLiteConnection _connection;

        public Repository(ISQLiteConnectionFactory factory)
        {
            _connection = factory.Create(new Guid().ToString() + "itemcollect.sql");
            _connection.CreateTable<T>();
        }

        public IList<T> All()
        {
            return _connection.Table<T>()
                .ToList();
        }

        public T Latest(Func<T, object> func)
        {
            return _connection
                .Table<T>()
                .OrderByDescending(func)
                .FirstOrDefault();
        }

        public T Get(int id)
        {
            return _connection.Get<T>(id);
        }

        public void Add(T item)
        {
            _connection.Insert(item);
        }

        public void Delete(T item)
        {
            _connection.Delete<T>(item);
        }

        public void Update(T item)
        {
            _connection.Update(item);
        }

        public List<T> Filter(Func<T, bool> func)
        {
            return _connection.Table<T>()
                       .Where(func)
                       .ToList();
        }

        public int Count()
        {
            return _connection.Table<T>().Count();
        }

        public void Dispose()
        {
            _connection.Close();
        }
    }
}
